<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="available">
        <el-select v-model="queryParams.available"  clearable @keyup.enter.native="handleQuery">
          <el-option value="" label="全部">全部</el-option>
          <el-option value="1" label="启用">启用</el-option>
          <el-option value="0" label="停用">停用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ProductPropertyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" show-overflow-tooltip width="200px"/>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="是否必填" align="center" prop="isRequired">
        <template slot-scope="scope">
          <span>{{scope.row.isRequired==0?"否":"是"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="字段类型" align="center" prop="columnType" >
        <template slot-scope="scope">
          <span>{{scope.row.columnType==1?"多选":scope.row.columnType==2?"单选":"手动录入"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="propertyType" >
        <template slot-scope="scope">
          <span>{{scope.row.propertyType===1?"通用属性":scope.row.propertyType===2?"指定类目属性":"无"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="available" >
        <template slot-scope="scope">
          <span>{{scope.row.available==1?"启用":"停用"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleValue(scope.row)"
          >属性值管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"  label-width="80px">
<!--        <el-form-item label="编号" prop="code">-->
<!--          <el-input v-model="form.code" placeholder="请输入编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-select v-model="form.isRequired" placeholder="请选择是否必填">
            <el-option label="是" :value="1">是</el-option>
            <el-option label="否" :value="0">否</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="字段类型" prop="columnType" >
          <el-select v-model="form.columnType" placeholder="请选择字段类型">
            <el-option label="多选" :value="1">多选</el-option>
            <el-option label="单选" :value="2">单选</el-option>
            <el-option label="手动录入" :value="3">手动录入</el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="类别" prop="propertyType">
          <el-select v-model="form.propertyType" placeholder="请选择类别">
            <el-option label="通用属性" :value="1">通用属性</el-option>
            <el-option label="指定类目属性" :value="2">指定类目属性</el-option>
            <el-option label="无" :value="3">无</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品类目" prop="categoryId" v-if="form.propertyType == 2">
          <el-checkbox-group v-model="formCategory" size="medium">
            <el-checkbox @change="handleNew"  v-for="(item, index) in formData" :key="index" :label="item.id"
                         :disabled="item.disabled">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="状态" prop="available" v-if="form.id != null">
          <el-select v-model="form.available" @keyup.enter.native="handleQuery">
            <el-option :value="1" label="启用">启用</el-option>
            <el-option :value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 商品属性值管理 -->
    <el-dialog title="商品属性值管理" :visible.sync="opens" width="1200px" append-to-body>
      <el-form :model="queryParams1" ref="queryform" size="small" :inline="true" v-show="showSearch1" label-width="68px">
        <el-form-item label="编号" prop="code">
          <el-input
            v-model="queryParams1.code"
            placeholder="请输入编号"
            clearable
            @keyup.enter.native="handleQuery1"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams1.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter.native="handleQuery1"
          />
        </el-form-item>
        <el-form-item label="状态" prop="available">
          <el-select v-model="queryParams1.available"  clearable @keyup.enter.native="handleQuery">
            <el-option value="" label="全部">全部</el-option>
            <el-option value="1" label="启用">启用</el-option>
            <el-option value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="reset1Query">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd1"
            v-hasPermi="['system:ProductPropertyItem:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch1.sync="showSearch1" @queryTable="getList1"></right-toolbar>
      </el-row>

      <el-table v-loading1="loading1" :data="ProductPropertyItemList" @selection-change="handleSelectionChange1">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="code"  show-overflow-tooltip width="200px"/>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="状态" align="center" prop="available" >
          <template slot-scope="scope">
            <span>{{scope.row.available==1?"启用":"停用"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="description" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate1(scope.row)"
              v-hasPermi="['system:ProductPropertyItem:edit']"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改商品属性值对话框 -->
    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="80px">
<!--        <el-form-item label="编号" prop="code">-->
<!--          <el-input v-model="form1.code" placeholder="请输入编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="名称" prop="name">
          <el-input v-model="form1.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="状态" prop="available" v-if="form1.id != null">
          <el-select v-model="form1.available" @keyup.enter.native="handleQuery">
            <el-option :value="1" label="启用">启用</el-option>
            <el-option :value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input v-model="form1.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitform1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductProperty, getProductProperty, addProductProperty, updateProductProperty,listProductPropertyItem, getProductPropertyItem, delProductPropertyItem, addProductPropertyItem, updateProductPropertyItem } from "@/api/system/ProductProperty";
import { listCategoryProperty,addCategoryProperty,getCategoryProperty } from "@/api/system/CategoryProperty";

export default {
  name: "ProductProperty",
  dicts: ['sys_yes_no'],
  data() {
    return {
      codeNum:null,
      codeNum1:null,
      CategoryProperty:[],
      formCategory:[],
      formData:[],
      opens:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品属性表格数据
      ProductPropertyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        available: null,
      },
      queryParams2: {
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        isRequired: [
          { required: true, message: "是否必填不能为空", trigger: "change" }
        ],
        columnType: [
          { required: true, message: "录入类型不能为空", trigger: "change" }
        ],
        propertyType: [
          { required: true, message: "属性类别不能为空", trigger: "change" }
        ],
        available: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        categoryId:[{
          required: true,
          message: '至少选择一个商品类目',
          trigger: 'change'
        }]
      },


      // 选中数组
      ids1: [],
      // 非单个禁用
      single1: true,
      // 非多个禁用
      multiple1: true,
      // 显示搜索条件
      showSearch1: true,
      // 商品属性值表格数据
      ProductPropertyItemList: [],
      // 弹出层标题
      title1: "",
      // 是否显示弹出层
      open1: false,
      // 查询参数
      queryParams1: {
        code: null,
        name: null,
        available: null,
        propertyId:null
      },
      // 表单参数
      form1: {},
      // 表单校验
      rules1: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        available: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }

    };
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {

    /** 查询商品类目列表 */
    getCategoryList() {
      this.loading = true;
      listCategoryProperty().then(response => {
        this.formData = response.rows;
        this.loading = false;
      });
    },
    /** 查询商品属性列表 */
    getList() {
      this.loading = true;
      listProductProperty(this.queryParams).then(response => {
        this.ProductPropertyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        isRequired: null,
        columnType: null,
        columnDataType: null,
        propertyType: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        categoryId:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //实时更新复选框商品类目信息
    handleNew(){
      this.form.categoryId = this.formCategory;
    },
    /** 新增按钮操作 */
    handleAdd() {
      //清空商品类目
      this.formCategory=[];
      this.reset();
      this.open = true;
      this.title = "添加商品属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //清空商品类目
      this.formCategory = [];
      this.reset();
      const id = row.id || this.ids
      getProductProperty(id).then(response => {
        this.form = response.data;
        //显示商品类目
        if (this.form.propertyType==2){
          //获取商品属性id
          let pid = this.form.id;
          //根据商品属性id查询对应的商品类目
          getCategoryProperty(pid).then(response => {
            this.CategoryProperty = response.data;
            this.form.categoryId = this.CategoryProperty.categoryId;  //为form中的categoryId赋值
            this.formCategory = this.CategoryProperty.categoryId.split(",");
          });
        }
        this.open = true;
        this.title = "修改商品属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
              //判断是否选择指定商品类目
              if (this.form.propertyType==2){
                let str = "";
                //循环商品类目拼接
                for(let i=0; i<this.formCategory.length; i++){
                  if (i>=this.formCategory.length-1){
                    str+=this.formCategory[i];
                    break;
                  }
                  str+=this.formCategory[i]+",";
                }
                this.form.categoryId = str;
              }
              updateProductProperty(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
          } else {
              //判断是否选择指定商品类目
              if (this.form.propertyType==2){
                let str = "";
                //循环商品类目拼接
                for(let i=0; i<this.formCategory.length; i++){
                  if (i>=this.formCategory.length-1){
                    str+=this.formCategory[i];
                    break;
                  }
                  str+=this.formCategory[i]+",";
                }
                this.form.categoryId = str;
              }
              const Code = getOrderCode(this.ProductPropertyList);
              this.form.code = Code;
              addProductProperty(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
        }
      });
    },

    handleValue(row){
        this.opens = true;
        this.loading = true;
        this.queryParams1.propertyId = row.id;
        listProductPropertyItem(this.queryParams1).then(response => {
          this.ProductPropertyItemList = response.rows;
          this.total1 = response.total1;
          this.loading = false;
        });
        // this.getList1();
    },

    /** 查询商品属性值列表 */
    getList1() {
      this.loading = true;
      listProductPropertyItem(this.queryParams1).then(response => {
        this.ProductPropertyItemList = response.rows;
        this.total1 = response.total1;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel1() {
      this.open1 = false;
      this.reset1();
    },
    // 表单重置
    reset1() {
      this.form1 = {
        id: null,
        code: null,
        name: null,
        propertyId: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery1() {
      this.getList1();
    },
    /** 重置按钮操作 */
    reset1Query() {
      this.queryParams1.code=null;
      this.queryParams1.name = null;
      this.queryParams1.available = null;
      this.handleQuery1();
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.ids1 = selection.map(item => item.id)
      this.single1 = selection.length!==1
      this.multiple1 = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd1() {
      this.reset1();
      this.open1 = true;
      this.title1 = "添加商品属性值";
    },
    /** 修改按钮操作 */
    handleUpdate1(row) {
      this.reset1();
      const id = row.id || this.ids1
      getProductPropertyItem(id).then(response => {
        this.form1 = response.data;
        this.open1 = true;
        this.title1 = "修改商品属性值";
      });
    },
    /** 提交按钮 */
    submitform1() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1.id != null) {
              updateProductPropertyItem(this.form1).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open1 = false;
                this.getList1();
              });
          } else {
              this.form1.propertyId = this.queryParams1.propertyId;
              const Code = getOrderCodeItem(this.ProductPropertyItemList);
              this.form1.code = Code;
              addProductPropertyItem(this.form1).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open1 = false;
                this.getList1();

              });
          }
        }
      });
    },
  }
};

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="SPSX"; //商品属性
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}



//单号生成
function getOrderCodeItem(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="SPXZ"; //商品属性值
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
